
package com.health.redis;



import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;

import org.apache.commons.compress.compressors.CompressorInputStream;
import org.apache.commons.compress.compressors.CompressorOutputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream;
import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.RedisZSetCommands.Tuple;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPoolConfig;

import com.alibaba.fastjson.JSONArray;
import com.health.db.model.RegisterOrder;
import com.health.db.service.sm.IRedisSentinelTemplateService;
import com.health.db.service.sm.impl.RedisSentinelTemplateServiceImpl;
import com.health.mapp.service.Service;
import com.health.mapp.utils.Byte2ObjectUtil;
import com.health.mapp.utils.PropertiesUtil;


 

 

public class RedisOperatiorLogic {

	private static Logger logger = Logger.getLogger(RedisOperatiorLogic.class);
	 
	
	private static ConcurrentHashMap<String, RedisTemplate<String, Object>> redisRegexTemplateMap = new ConcurrentHashMap<String, RedisTemplate<String, Object>>();

	private static ConcurrentHashMap<String, RedisTemplate<String, Object>> redisTemplateMap = new ConcurrentHashMap<String, RedisTemplate<String, Object>>();

	private static ConcurrentHashMap<String, ConcurrentHashMap<String, RedisTemplate<String, Object>>> cacheMap = new ConcurrentHashMap<String, ConcurrentHashMap<String, RedisTemplate<String, Object>>>();
 
	
	private int setExTimeout = 180;
	
	 
 
	private Jedis jedis;
	private boolean jedisIsConnected=false;
	
	public boolean isJedisIsConnected() {
		return jedisIsConnected;
	}

	public void setJedisIsConnected(boolean jedisIsConnected) {
		this.jedisIsConnected = jedisIsConnected;
	}

	private IRedisSentinelTemplateService redisSentinelTemplateService=  new RedisSentinelTemplateServiceImpl();
	
	 

 
	public IRedisSentinelTemplateService getRedisSentinelTemplateService() {
		return redisSentinelTemplateService;
	}

	public void setRedisSentinelTemplateService(
			IRedisSentinelTemplateService redisSentinelTemplateService) {
		this.redisSentinelTemplateService = redisSentinelTemplateService;
	}


	public boolean jedisTextX() 
	{	  String host = "";// "localhost";
	  int port = 6379;// 6379;
		try
		{
			host = PropertiesUtil.getString("Test.Redis.server.host");// "localhost";
			port = Integer.parseInt(PropertiesUtil
					.getString("Test.Redis.server.port"));
			   logger.debug("Test.Redis.server.host:"+host);
			   logger.debug("Test.Redis.server.port:"+port);
		     //连接redis服务器，192.168.0.100:6379
	         jedis = new Jedis(host, port);
	         if(null!=jedis )
	         {
	        	 //connect 
	        	 jedis.connect();
		         //权限认证
			     // jedis.auth("admin");  
	        	 jedisIsConnected=jedis.isConnected();
		         logger.debug("jedis isConnected:"+jedisIsConnected);
		         jedis.disconnect();
	         }
	        
		}
		catch(Exception e)
		{
 
			 e.printStackTrace();
			 jedisIsConnected=jedis.isConnected();
	         logger.error("jedis isConnected:"+jedisIsConnected);
	         jedis.disconnect();
		}
		return jedisIsConnected;
	}

	public void jedisSetup() {

	
	}
	
	
	
	//  
	public void init() {
	 
	 if (jedisTextX()) {
			//this.loadCache();
			this.loadSentinelCache();
		 }

	
		
	}
	
 
	public RedisTemplate<String, Object> getTemplateByGroup(final String group) {
		return redisTemplateMap.get(group);
	}

 
	public RedisTemplate<String, Object> getTemplateByNum(
			final String numberSequence) {
		for (Enumeration<String> enumeration = redisRegexTemplateMap.keys(); enumeration
				.hasMoreElements();) {
			String key = enumeration.nextElement();

			if (Pattern.matches(key, numberSequence)) {
				return redisRegexTemplateMap.get(key);
			}
		}

		return null;

	}
	
 
	public void loadSentinelCache() {

		String[] bigGroupList = RedisConstants.REDIS_BIG_GROUP.split(",");
		StringBuffer buf = new StringBuffer();
		for(String bigGroupNo : bigGroupList){
			buf.append("'" + bigGroupNo + "',");
		}
		logger.debug("redisSentinelTemplateService:"+redisSentinelTemplateService);

		List<Map<String, Object>> tList = redisSentinelTemplateService.getRedisSentinelTemplate(buf.deleteCharAt(buf.length() - 1).toString());
		try {
			logger.debug("Redis Sentinel template load start");

			if(null==tList)
			{
				logger.debug("GlobalConfig is null,Redis Sentinel template load failed!");
				return;
			}
			for (Iterator<Map<String, Object>> iterator = tList.iterator(); iterator
					.hasNext();) {
				Map<String, Object> tMap = iterator.next();

				String templateCode = tMap.get("TEMPLATE_CODE").toString();
				String masterName = tMap.get("MASTER_NAME").toString();
				String sentinelProperiesContent = tMap.get(
						"SENTINEL_PROPERTIES").toString();
				String big_group = tMap.get("BIG_GROUP").toString();
				String msg_type = tMap.get("MSG_TYPE").toString();

				String poolProperiesContent = tMap.get("POOL_PROPERTIES")
						.toString().replaceAll(" ", "\n");

				Set<RedisNode> redisNodes = new HashSet<RedisNode>();
				String[] sentinelList = sentinelProperiesContent
						.split("\\|\\|");
				for (int i = 0; i < sentinelList.length; i++) {
					String redisNodeInfo = sentinelList[i]
							.replaceAll(",", "\n");
					String host = null;
					int port = 0;
					final Properties fp = new Properties();
					fp.load(new StringReader(redisNodeInfo));
					for (Enumeration<Object> enumeration = fp.keys(); enumeration
							.hasMoreElements();) {
						String key = enumeration.nextElement().toString();

						if ("host".equalsIgnoreCase(key)) {
							host = fp.getProperty(key).trim();
						} else {
							port = Integer.parseInt(fp.getProperty(key).trim());
						}
					}
					RedisNode redisNode = new RedisNode(host, port);
					redisNodes.add(redisNode);
				}

				RedisSentinelConfiguration redisSentinelConfiguration = new RedisSentinelConfiguration();
				redisSentinelConfiguration.setMaster(masterName);
				redisSentinelConfiguration.setSentinels(redisNodes);

				JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
				final Properties pp = new Properties();
				pp.load(new StringReader(poolProperiesContent));

				for (Enumeration<Object> enumeration = pp.keys(); enumeration
						.hasMoreElements();) {
					String key = enumeration.nextElement().toString();

					Method[] methods = JedisPoolConfig.class.getMethods();
					String methodName = "set"
							+ key.substring(0, 1).toUpperCase()
							+ key.substring(1);
					for (Method m : methods) {
						if (methodName.equals(m.getName())) {

							Object value = null;
							value = castStringToX(m.getParameterTypes()[0],
									pp.getProperty(key));

							m.invoke(jedisPoolConfig, value);
							break;
						}
					}
				}

				JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(
						redisSentinelConfiguration, jedisPoolConfig);
				jedisConnectionFactory.setPassword( PropertiesUtil.getString("Test.Redis.server.password"));
				
				jedisConnectionFactory.afterPropertiesSet();

				jedisConnectionFactory.setPoolConfig(jedisPoolConfig);
				
				RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
				redisTemplate.setConnectionFactory(jedisConnectionFactory);
				redisTemplate.afterPropertiesSet();

				// begin
				Object regex = tMap.get("REGEX");
				if(regex!=null){
					redisRegexTemplateMap.put(regex.toString(), redisTemplate);
				}
				//redisTemplateMap.put(templateCode, redisTemplate);
				redisTemplateMap.put(msg_type + RedisConstants.REDIS_GROUP_SEPARATOR + big_group, redisTemplate);
				//System.out.println("redisTemplateMap" + redisTemplateMap );
				
				cacheMap.put("redisRegexTemplateMap", redisRegexTemplateMap);
				cacheMap.put("redisTemplateMap", redisTemplateMap);
				// end
				logger.debug("Redis template load[" + templateCode + "]: <"
						+ regex + "> completely");
				jedisIsConnected=true;
				logger.debug("jedisIsConnected: <"
						+ jedisIsConnected + "> ");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage()+e);
		}
	}
	
	 
	public void loadCache() {

		List<Map<String, Object>> tList = redisSentinelTemplateService.getRedisTemplate();
		try {
			 
			for (Iterator<Map<String, Object>> iterator = tList.iterator(); iterator
					.hasNext();) {
				Map<String, Object> tMap = iterator.next();

				String templateCode = tMap.get("TEMPLATE_CODE").toString();
				//String factoryProperiesContent = tMap.get("FACTORY_PROPERTIES").toString().replaceAll(" ", "\n");
				String poolProperiesContent = tMap.get("POOL_PROPERTIES")
						.toString().replaceAll(" ", "\n");

				final Properties fp = new Properties();
				//fp.load(new StringReader(factoryProperiesContent));
				JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();

				for (Enumeration<Object> enumeration = fp.keys(); enumeration
						.hasMoreElements();) {
					String key = enumeration.nextElement().toString();

					Method[] methods = JedisConnectionFactory.class
							.getMethods();
					String methodName = "set"
							+ key.substring(0, 1).toUpperCase()
							+ key.substring(1);
					for (Method m : methods) {
						if (methodName.equals(m.getName())) {

							Object value = null;
							value = castStringToX(m.getParameterTypes()[0],
									fp.getProperty(key));
							m.invoke(jedisConnectionFactory, value);
							break;
						}
					}
				}
				jedisConnectionFactory.afterPropertiesSet();

				JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
				final Properties pp = new Properties();
				pp.load(new StringReader(poolProperiesContent));

				for (Enumeration<Object> enumeration = pp.keys(); enumeration
						.hasMoreElements();) {
					String key = enumeration.nextElement().toString();

					Method[] methods = JedisPoolConfig.class.getMethods();
					String methodName = "set"
							+ key.substring(0, 1).toUpperCase()
							+ key.substring(1);
					for (Method m : methods) {
						if (methodName.equals(m.getName())) {

							Object value = null;
							value = castStringToX(m.getParameterTypes()[0],
									pp.getProperty(key));

							m.invoke(jedisPoolConfig, value);
							break;
						}
					}
				}
				jedisConnectionFactory.setPoolConfig(jedisPoolConfig);

				RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
				redisTemplate.setConnectionFactory(jedisConnectionFactory);
				redisTemplate.afterPropertiesSet();

				// begin
				Object regex = tMap.get("REGEX");
				if(regex!=null){
					redisRegexTemplateMap.put(regex.toString(), redisTemplate);
				}
				redisTemplateMap.put(templateCode, redisTemplate);
				
				cacheMap.put("redisRegexTemplateMap", redisRegexTemplateMap);
				cacheMap.put("redisTemplateMap", redisTemplateMap);
				// end
			 
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
	}
	
	private Object castStringToX(Class<?> clazz, String str) {
		Object value = null;
		if (clazz.getName().equals("java.lang.Integer")
				|| clazz.getName().equals("int")) {
			value = Integer.parseInt(str);
		} else if (clazz.getName().equals("java.lang.Boolean")
				|| clazz.getName().equals("boolean")) {
			value = Boolean.parseBoolean(str);
		} else if (clazz.getName().equals("java.lang.Long")
				|| clazz.getName().equals("long")) {
			value = Long.parseLong(str);
		} else {
			value = str;
		}
		return value;
	}


	
	/**
	 *  将一个用户的一个新增加订单数据放入到内存库，也可以是一个用户的其他数据
	 * @param zAddKey  order:userId:userId-value
	 * @param hSetKey  order:orderId:
	 * @param zAddValue  orderId:orderId-value
	 * @param score       currentTimeMillis
	 * @param content    content
	 * @param groupNo    groupNo
	 */
	
	  public   void setSortedSetPagenation(final String zAddKey,final String hSetKey,final String zAddValue,    final double score,  final Object content,String groupNo)
	  {
 
			RedisTemplate<String, Object> redisTemplate = this.getTemplateByGroup(groupNo);
			
			redisTemplate.execute(new RedisCallback<Object>() {   
		        @Override  
		        public Object doInRedis(RedisConnection connection)   
		                throws DataAccessException {   
		        	
 
		        	connection.zAdd(  zAddKey.getBytes(), score,  zAddValue.getBytes());
		        	connection.hSet(hSetKey.getBytes(),zAddValue.getBytes(), Byte2ObjectUtil.objectToByte(content));
		        	
		            return null;   
		        }   
		    }); 
		
		 	
		
	    }
	  
	  
	  /**
	   * 
	   * @param zAddKey
	   * @param hSetKey
	   * @param groupNo
	   */
	  public   void updateSortedSetPagenation(final String zAddKey,final String hSetKey ,String groupNo)
	  {
 
			RedisTemplate<String, Object> redisTemplate = this.getTemplateByGroup(groupNo);
			
			redisTemplate.execute(new RedisCallback<Object>() {   
		        @Override  
		        public Object doInRedis(RedisConnection connection)   
		                throws DataAccessException {   
		        	
		        	Long result1 = connection.del(zAddKey.getBytes());  
                    Long result2 = connection.del(hSetKey.getBytes());   
		            return null;   
		        }   
		    }); 
		
		 	
		
	    }
	 
	  /**
	   * 
	   * @param zAddKey
	   * @param hSetKey
	   * @param groupNo
	   */
	  public   void deleteSortedSetPagenation(final String zAddKey,final String hSetKey ,    String groupNo)
	  {
 
			RedisTemplate<String, Object> redisTemplate = this.getTemplateByGroup(groupNo);
			
			redisTemplate.execute(new RedisCallback<Object>() {   
		        @Override  
		        public Object doInRedis(RedisConnection connection)   
		                throws DataAccessException {   
		        	
 
		        	//connection.zAdd(  zAddKey.getBytes(), score,  zAddValue.getBytes());
		        	//connection.hSet(hSetKey.getBytes(),zAddValue.getBytes(), Byte2ObjectUtil.objectToByte(content));
                    Long result1 = connection.del(zAddKey.getBytes());  
                    Long result2 = connection.del(hSetKey.getBytes());     
		              
		            
		            return null;   
		        }   
		    }); 
		
		 	
		
	    }
	  /**
	   * 取到一个用户关系数据中的第offset开始的count条数据并以List返回
	   * @param zAddKey  order:userId:userId-value
	   * @param hSetKey  order:orderId:
	   * @param min       9999999999999
	   * @param max       0
	   * @param offset   offset
	   * @param count     count
	   * @param groupNo   groupNo
	   * @return
	   */
		public   Object getSortedSetPagenation(final String zAddKey,final String hSetKey,final double min,final double max, final long offset, final long count,String groupNo){
		 
					
		         
		    		  
				   RedisTemplate<String, Object> redisTemplate = this.getTemplateByGroup(groupNo);
					
					Object result =  redisTemplate
							.execute(new RedisCallback<Object>() {
								@Override
								public Object doInRedis(RedisConnection connection)
										throws DataAccessException {
 
									 
									// 倒序取 从第offset条开始取count条 Id 数据
									Set<Tuple> sets =   connection.zRevRangeByScoreWithScores(zAddKey.getBytes(), min, max, offset, count);
									String[] items = new String[]{};
									//根据Id取到所有 对象数据
									List<byte[]> b=connection.hMGet(hSetKey.getBytes(), Byte2ObjectUtil.objectToByte(sets.toArray(items)));
									List<Object> list = new ArrayList<Object>();
									if (b != null) {
										for(byte[] temp:b)
										{
											Object val = Byte2ObjectUtil.byteToObject(temp);
											list.add(val);
										}
										
										 return list;
										 
									} 
									return null;

								}
							});
					if(result!=null){
						return result;
					}
					return null;
		        
		        
			
		}
		
		/**
		 * 在limitingTime内如果IP出现的次数超过了IPLimit，说明有人恶意访问，需要不让其访问
		 * @param IP  限制的IP或是其他唯一标识用户的数据 
		 * @param IPLimit  限制的次数
		 * @param limitingTime  限制的时间，
		 * @param groupNo
		 * @return
		 */
		  public   boolean visiterIPLimit(final String IP,final long IPLimit, final long limitingTime,String groupNo)
		  {

				 
				RedisTemplate<String, Object> redisTemplate = this.getTemplateByGroup(groupNo);
				
				redisTemplate.execute(new RedisCallback<Object>() {   
			        @Override  
			        public Object doInRedis(RedisConnection connection)   
			                throws DataAccessException {   
			        	

						  String keyName="rate.limiting:"+IP;
			        	 //IP是否已存在
				           boolean   isKeyExists =  connection.exists( keyName.getBytes());
							  
				           if (isKeyExists ==true)
				           {
				        	   //存在则判断现在已经访问多少次了
				        	   long times = connection.incr( keyName.getBytes());
				           
				        	   if (times > IPLimit)
				        	   {
				                
				        		   System.out.print(" 访问频率超过了限制，请稍后再试");
				        		   return false;
				        
				        	   }
				           }
				          else{
				               // MULTI
				        	   connection.multi();
				        	   connection.incr(keyName.getBytes());
				        	   connection.expire(keyName.getBytes(), limitingTime); //这个用事务控制，否则这行如果没有执行，那用户最多只能访问100次博客了
				               //EXEC
				        	   connection.exec();
				              
				           }
			            return true;   
			        }   
			    }); 
			
		    
				
				    
				return true;
			
		    }
		    
		  
	public Object lpop(final String key, String groupNo) throws Exception {
		
 
		RedisTemplate<String, Object> redisTemplate = this.getTemplateByGroup(groupNo);
		
		Object result =  redisTemplate
				.execute(new RedisCallback<Object>() {
					@Override
					public Object doInRedis(RedisConnection connection)
							throws DataAccessException {
						// connection.rp
						
						byte[] b = connection.lPop(key.getBytes());
						if (b != null) {
							Object val = Byte2ObjectUtil.byteToObject(b);
							 return val;
							//return new String(b);
						} 
						return null;

					}
				});
		if(result!=null){
			return result;
		}
		return null;
	}
	
	public Object rpop(final String key, String groupNo) throws Exception {
		
		 
		RedisTemplate<String, Object> redisTemplate = this.getTemplateByGroup(groupNo);
		
		Object result =  redisTemplate
				.execute(new RedisCallback<Object>() {
					@Override
					public Object doInRedis(RedisConnection connection)
							throws DataAccessException {
						// connection.rp
						
						byte[] b = connection.rPop(key.getBytes());
						if (b != null) {
							Object val = Byte2ObjectUtil.byteToObject(b);
							 return val;
							//return new String(b);
						} 
						return null;

					}
				});
		if(result!=null){
			return result;
		}
		return null;
	}
	public void rpush(final String key, final Object value, String groupNo)  {
		
 
		RedisTemplate<String, Object> redisTemplate = this.getTemplateByGroup(groupNo);
		
		redisTemplate.execute(new RedisCallback<Object>() {   
	        @Override  
	        public Object doInRedis(RedisConnection connection)   
	                throws DataAccessException {   
	        	
	        	connection.rPush(key.getBytes(), Byte2ObjectUtil.objectToByte(value));
	        	
	            return null;   
	        }   
	    }); 
	}
	
	
	
	public void lpush(final String key, final String value, String groupNo)  {
		
		 
		RedisTemplate<String, Object> redisTemplate = this.getTemplateByGroup(groupNo);
		
		redisTemplate.execute(new RedisCallback<Object>() {   
	        @Override  
	        public Object doInRedis(RedisConnection connection)   
	                throws DataAccessException {   
	        	
	        	if (connection.exists(key.getBytes())) {
	        		connection.expire(key.getBytes(), setExTimeout);
				}
	        	//JSONArray.to
	        	
	        	connection.lPush(key.getBytes(),value.getBytes());
	        	
	            return null;   
	        }   
	    }); 
	}
	 
	
	public boolean exists(final String key, String groupNo)  {
		 
		RedisTemplate<String, Object> redisTemplate = this.getTemplateByGroup(groupNo);
		return
			(Boolean) redisTemplate.execute(new RedisCallback<Object>() {   
		        @Override  
		        public Object doInRedis(RedisConnection connection)   
		                throws DataAccessException {   
		        	
		        	if (connection.exists(key.getBytes())) {
		        		return true;
					}
		        	
		            return false;   
		        }   
		    }); 
	}
	
	
	public List lRange(final String key, String groupNo)  {
		
		 
		RedisTemplate<String, Object> redisTemplate = this.getTemplateByGroup(groupNo);
		

		List obj = null;
		obj = (List) redisTemplate
				.execute(new RedisCallback<Object>() {

					public Object doInRedis(RedisConnection connection)
							throws DataAccessException {
				 
						if (connection.exists(key.getBytes())) {
							List valueSrc = connection.lRange(key.getBytes(),0,-1);
							
							return valueSrc;
						}else{
							return null;
						}
						
					}
				});
		return obj;
		
	}
	 
 
	 
	
 
	public Object hGet(final String key, final String field, String groupNo) throws Exception {
		 

	 
		RedisTemplate<String, Object> redisTemplate = this
				.getTemplateByGroup(groupNo);

		if (redisTemplate == null) {
			throw new Exception("Can't get redisTemplate correctly by groupNo["+groupNo+"]");
		}

		 

		Object obj = null;
		obj = (Object) redisTemplate
				.execute(new RedisCallback<Object>() {

					public Object doInRedis(RedisConnection connection)
							throws DataAccessException {
				 
						byte[] valueSrc = connection.hGet(key.getBytes(), field.getBytes());
						Object value = null;
						if("true".equalsIgnoreCase("GLOBLE_REDIS_COMPRESS")){
					 
							value =  valueSrc==null ? null : Byte2ObjectUtil.byteToObject(uzip(valueSrc));
						}else{
							value =  valueSrc==null ? null : Byte2ObjectUtil.byteToObject(valueSrc);
						}
							
						return value;
					}
				});

		return obj;
	}
	
 
	public void hSet(final String key, final String field, final Object obj, String groupNo ) {
		
	 
		RedisTemplate<String, Object> redisTemplate = this
				.getTemplateByGroup(groupNo);
		
		redisTemplate.execute(new RedisCallback<Object>() {

			@Override
			public Object doInRedis(RedisConnection connection)
					throws DataAccessException {
				if ("true".equalsIgnoreCase("GLOBLE_REDIS_COMPRESS")) {
					connection.hSet(key.getBytes(), field.getBytes(), zip(Byte2ObjectUtil.objectToByte(obj)));
				} else {
					connection.hSet(key.getBytes(), field.getBytes(), Byte2ObjectUtil.objectToByte(obj));
				}

				return null;
			}
		});
	}
	
 
	public void hDel(final String key, final String field, String groupNo) throws Exception {
		 
		RedisTemplate<String, Object> redisTemplate = this
				.getTemplateByGroup(groupNo);

	 

		if (redisTemplate == null) {
			throw new Exception("Can't get redisTemplate correctly by group ");
		}
		redisTemplate.execute(new RedisCallback<Object>() {
			public Object doInRedis(RedisConnection connection) {
				return connection.hDel(key.getBytes(), field.getBytes());
			}
		});
	}
	 
 
	 
	public Object readObject(final String key, String groupNo)  {
		 
		Object obj = null;
		
		RedisTemplate<String, Object> redisTemplate = this
				.getTemplateByGroup(groupNo);
	
		try{
			obj = (Object) redisTemplate
					.execute(new RedisCallback<Object>() {
	
						public Object doInRedis(RedisConnection connection)
								throws DataAccessException {
							byte[] valueSrc = connection.get(key.getBytes());
							Object value = null;
							if("true".equalsIgnoreCase("GLOBLE_REDIS_COMPRESS")){
							 
								value =  valueSrc==null ? null : Byte2ObjectUtil.byteToObject(uzip(valueSrc));
							}else{
								value =  valueSrc==null ? null : Byte2ObjectUtil.byteToObject(valueSrc);
							}
								
							return value;
						}
					});
		} catch (Exception e) {
			e.printStackTrace();
		}
		return obj;
	}
	
	public void setObject(final String key, final Object obj, String groupNo)
			throws Exception {
		
 
		RedisTemplate<String, Object> redisTemplate = this
				.getTemplateByGroup(groupNo);
		
		try{
		 redisTemplate.execute(new RedisCallback<Object>() {
			@Override
			public Object doInRedis(RedisConnection connection)throws DataAccessException {
				
				if ("true".equalsIgnoreCase("GLOBLE_REDIS_COMPRESS")) {
					connection.set(key.getBytes(), zip(Byte2ObjectUtil.objectToByte(obj)));
					
				} else {
					connection.set(key.getBytes(), Byte2ObjectUtil.objectToByte(obj));
				}
				logger.debug("set success!");
				return 1;
			}
		});
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void deleteObject(final String key, String groupNo)  {
		 
		RedisTemplate<String, Object> redisTemplate = this
				.getTemplateByGroup(groupNo);

		try{
		 redisTemplate.execute(new RedisCallback<Object>() {
			public Object doInRedis(RedisConnection connection) {
				return connection.del(key.getBytes());
			}
		});
		}catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	/**
	 * 
	 * @param key
	 * @param obj
	 * @param groupNo
	 * @return
	 * @throws Exception
	 */
	public void setEx(final String key, final int timeout,  Object obj, String groupNo) {
 
		RedisTemplate<String, Object> redisTemplate = this
				.getTemplateByGroup(groupNo);
		if (null==obj) {
			obj="";
		}
		final Object objj=obj;
		try{
		redisTemplate.execute(new RedisCallback<Object>() {
			
			@Override
			public Object doInRedis(RedisConnection connection)
					throws DataAccessException {
				if ("true".equalsIgnoreCase("GLOBLE_REDIS_COMPRESS")) {
					connection.setEx(key.getBytes(), setExTimeout,zip(Byte2ObjectUtil.objectToByte(objj)));
				} else {
					connection.setEx(key.getBytes(), timeout,	Byte2ObjectUtil.objectToByte(objj));
				}
				return 1;
			}
		});
		}
		catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	/**
	 * 
	 * @param key
	 * @param obj
	 * @param groupNo
	 * @return
	 * @throws Exception
	 */
	public void setEx(final String key,  Object obj, String groupNo) {
 
		RedisTemplate<String, Object> redisTemplate = this
				.getTemplateByGroup(groupNo);
		if (null==obj) {
			obj="";
		}
		final Object objj=obj;
		//System.out.println(redisTemplate);
		try{
		 redisTemplate.execute(new RedisCallback<Object>() {

			@Override
			public Object doInRedis(RedisConnection connection)
					throws DataAccessException {
				if ("true".equalsIgnoreCase("GLOBLE_REDIS_COMPRESS")) {
					
					connection.setEx(key.getBytes(), setExTimeout,zip(Byte2ObjectUtil.objectToByte(objj)));
				} else {
					connection.setEx(key.getBytes(), setExTimeout,Byte2ObjectUtil.objectToByte(objj));
				}
				return 1;
			}
		});
		 }catch (Exception e) {
		}
	}
	
	
	 
	long acquireLock(final String lockName, final long expire, String groupNo) {
		RedisTemplate<String, Object> redisTemplate = this
				.getTemplateByGroup(groupNo);
		return redisTemplate.execute(new RedisCallback<Long>() {
			public Long doInRedis(RedisConnection connection) {
				byte[] lockBytes = lockName.getBytes();
				boolean locked = connection.setNX(lockBytes, lockBytes);
				connection.expire(lockBytes, expire);
				if (locked) {
					return 1L;
				}
				return 0L;
			}
		});
	}
	
	public static byte[] zip(byte[] bytes) {

		ByteArrayOutputStream out = null;
		CompressorOutputStream cos = null;
		try {
			out = new ByteArrayOutputStream();
			cos = new GzipCompressorOutputStream(out);
			cos.write(bytes);
			cos.close();

			byte[] rs = out.toByteArray();
			out.close();
			return rs;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {

		}

		return null;
	}

	/**
	 * 
	 * @param bytes
	 * @return
	 */
	public static byte[] uzip(byte[] bytes) {

		CompressorInputStream cis = null;
		ByteArrayInputStream bais = null;
		ByteArrayOutputStream baos = null;
		try {
			bais = new ByteArrayInputStream(bytes);
			cis = new GzipCompressorInputStream(bais);
			baos = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int size = 0;
			while ((size = cis.read(buffer)) > 0) {
				baos.write(buffer, 0, size);
			}
			byte[] rs = baos.toByteArray();
			return rs;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (baos != null) {
				try {
					baos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (cis != null) {
				try {
					cis.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (bais != null) {
				try {
					bais.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}

		return null;
	}

	
	/**
	 * 模糊查询删除
	 * @param key
	 * @param groupNo
	 * @return
	 */
	public int deleteFuzzyObject(final String key, String groupNo)  {
		 
		RedisTemplate<String, Object> redisTemplate = this
				.getTemplateByGroup(groupNo);

		return ((Long) redisTemplate.execute(new RedisCallback<Object>() {
			public Object doInRedis(RedisConnection connection) {
				
				Set<byte[]> set = connection.keys((key+"*").getBytes());
				 
				 Iterator<byte[]> it = set.iterator();  
	             while (it.hasNext()) {  
	                byte[] temp = it.next();  
	                
	                connection.del(temp);
	             }  
	             connection.del(key.getBytes());
				return 1;
			}
		})).intValue();
	}
	
	

	public void deleteKeys(final String key, String groupNo)  {
		
		 
		RedisTemplate<String, Object> redisTemplate = this.getTemplateByGroup(groupNo);
		
		try{
		 redisTemplate.execute(new RedisCallback<Object>() {

					public Object doInRedis(RedisConnection connection)
							throws DataAccessException {
				 
						List<byte[]> valueSrc = connection.lRange(key.getBytes(),0,-1);
						
						int size = valueSrc.size();
						for (int i = 0; i < size; i++) {
							String res = new String(valueSrc.get(i));
							connection.del( res.getBytes());
						}
						return valueSrc;
					}
				});
		}catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	
	/**
	 * 
	 * @param key
	 * @param obj
	 * @param groupNo
	 * @return
	 * @throws Exception
	 */
	public void setKeys(final String key, final int timeout,  Object obj, String groupNo) {
 
		RedisTemplate<String, Object> redisTemplate = this
				.getTemplateByGroup(groupNo);
		if (null==obj) {
			obj="";
		}
		final Object objj=obj;
		try{
		redisTemplate.execute(new RedisCallback<Object>() {
			
			@Override
			public Object doInRedis(RedisConnection connection)
					throws DataAccessException {
				if ("true".equalsIgnoreCase("GLOBLE_REDIS_COMPRESS")) {
					connection.setEx(key.getBytes(), setExTimeout,zip(Byte2ObjectUtil.objectToByte(objj)));
				} else {
					connection.setEx(key.getBytes(), timeout,	Byte2ObjectUtil.objectToByte(objj));
				}
				return 1;
			}
		});
		}
		catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	
	

	/**
	 * 
	 * @param key
	 * @param obj
	 * @param groupNo
	 * @return
	 * @throws Exception
	 */
	public void setMapsOrders(final String key, final int timeout,  List<RegisterOrder> obj, String groupNo) {
 
		RedisTemplate<String, Object> redisTemplate = this
				.getTemplateByGroup(groupNo);
		if (null==obj) {
			obj= new ArrayList<RegisterOrder>();;
		}
		final  List<RegisterOrder> objj=obj;
		try{
		redisTemplate.execute(new RedisCallback<Object>() {
			
			@Override
			public Object doInRedis(RedisConnection connection)
					throws DataAccessException {
				
					//connection.setEx(key.getBytes(), timeout,	Byte2ObjectUtil.objectToByte(objj));
					
				/*	Map<String, String> orders = new HashMap<String,String>();
					
					int size=objj.size();
					for (int i = 0; i < size; i++) {
						RegisterOrder temp = objj.get(i);
						orders.put(key, value);
					}*/
			
					//connection.hMSet(arg0, arg1)
				return 1;
			}
		});
		}
		catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	
	
	public static void main(String[] args) {
		//RedisOperatiorLogic logic  = new RedisOperatiorLogic();
		 //String host = "59.110.17.33";// "localhost";
		  String host = "47.93.161.105";
		 // String host = "182.92.175.50";
		  int port = 7001;// 6379;
		  Jedis jedis = null;
		  boolean jedisIsConnected;	
			try
			{
			     //连接redis服务器，192.168.0.100:6379
		         jedis = new Jedis(host, port);
		         jedis.auth("shouer0621CHANGE");
		         System.out.println(jedis.info());
		         jedis.flushDB();
		         logger.debug(jedis.dbSize());
		        // jedis.set("123", "1111");
		         System.out.println(jedis.keys("*"));
		        //System.out.println(jedis.info());
		       //  System.out.println(jedis.lrange("29:docId:69", 0, -1));
//		         RegisterOrder order1 = new RegisterOrder();
//		         order1.setRegisterid(1l);
//		         
//		         RegisterOrder order2 = new RegisterOrder();
//		         order2.setRegisterid(2l);
//		         
//		           RegisterOrder order3 = new RegisterOrder();
//		         order3.setRegisterid(3l);
//		  
		   
		        
			}
			catch(Exception e)
			{
	 
				 e.printStackTrace();
				 jedisIsConnected=jedis.isConnected();
		         logger.error("jedis isConnected:"+jedisIsConnected);
		         jedis.disconnect();
			}
	}


}
